package com.kotlin.novel.ui

import android.content.Intent
import android.util.Log
import android.view.View
import android.widget.ImageView
import android.widget.TextView
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.kotlin.novel.R
import com.kotlin.novel.adapter.BookListAdapter
import com.kotlin.novel.base.BaseActivity
import com.kotlin.novel.listener.RVOScrollListener
import com.kotlin.novel.model.BookModel
import com.kotlin.novel.utils.HttpUtil
import kotlinx.android.synthetic.main.type_rank.*
import kotlinx.android.synthetic.main.type_small.*

import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.async
import kotlinx.coroutines.launch
import org.json.JSONObject


class BookTypeActivity : BaseActivity(), View.OnClickListener {
    private var currentPage: Int = 0
    private var totalPageCount: Int = 1
    private lateinit var weekRank: String
    private lateinit var monthRank: String
    private lateinit var totalRank: String

    private lateinit var type: String
    private lateinit var typeUrl: String
    private var limit = 20

    private lateinit var ivBack: ImageView
    private lateinit var tvTitle: TextView
    private lateinit var tvSearch: TextView
    private lateinit var tvWeek: TextView
    private lateinit var tvMonth: TextView
    private lateinit var tvTotal: TextView

    private lateinit var typeHot: TextView
    private lateinit var typeNew: TextView
    private lateinit var typeRepulation: TextView
    private lateinit var typeOver: TextView
    private var typeSmall = "hot"

    private lateinit var rvBooks: RecyclerView
    private lateinit var bookListAdapter: BookListAdapter

    private var bookModels = ArrayList<BookModel>()
    private lateinit var gender: String
    private var isLoading = false

    override fun getLayoutResId(): Int {
        return R.layout.activity_book_type
    }

    override fun initView() {
        ivBack = findViewById(R.id.iv_title_back)
        tvTitle = findViewById(R.id.tv_title)
        tvSearch = findViewById(R.id.tv_search)
        rvBooks = findViewById(R.id.rv_books)
        rvBooks.layoutManager = LinearLayoutManager(this)
    }

    override fun initData() {
        type = intent.getStringExtra("type")
        typeUrl = intent.getStringExtra("typeUrl")
        gender = intent.getStringExtra("gender")
        weekRank = intent.getStringExtra("typeUrl")
        totalRank = intent.getStringExtra("totalRank")
        monthRank = intent.getStringExtra("monthRank")

        if (typeUrl == "") {
            type_small.visibility = View.VISIBLE
            typeHot = findViewById(R.id.tv_type_hot)
            typeRepulation = findViewById(R.id.tv_type_repulation)
            typeNew = findViewById(R.id.tv_type_new)
            typeOver = findViewById(R.id.tv_type_over)

            typeHot.setOnClickListener(this)
            typeRepulation.setOnClickListener(this)
            typeNew.setOnClickListener(this)
            typeOver.setOnClickListener(this)

        }
        if (monthRank != "") {
            type_rank.visibility = View.VISIBLE
            tvMonth = findViewById(R.id.tv_rank_month)
            tvWeek = findViewById(R.id.tv_rank_week)
            tvTotal = findViewById(R.id.tv_rank_total)
            tvTotal.setOnClickListener(this)
            tvWeek.setOnClickListener(this)
            tvMonth.setOnClickListener(this)
        }


        tvTitle.text = type
        ivBack.setOnClickListener(this)
        tvSearch.setOnClickListener(this)

        getBookList(currentPage)

        bookListAdapter = BookListAdapter(this, bookModels)
        rvBooks.adapter = bookListAdapter
        rvBooks.addOnScrollListener(object : RVOScrollListener(rvBooks.layoutManager as LinearLayoutManager) {
            override fun loadMoreItems() {
                getBookList(currentPage)
            }

            override fun totalPageCount(): Int {
                return totalPageCount
            }

            override fun isLastPage(): Boolean {
                return currentPage >= totalPageCount
            }

            override fun isLoading(): Boolean {
                return isLoading
            }
        })
    }

    override fun onClick(v: View?) {
        when (v?.id) {
            R.id.iv_title_back -> {
                finish()
            }
            R.id.tv_search -> {
                startActivity(Intent(this, SearchActivity::class.java))
            }
            R.id.tv_rank_week -> {
                bookModels.clear()
                bookListAdapter.notifyDataSetChanged()
                typeUrl = weekRank
                currentPage = 0
                getBookList(0)
            }
            R.id.tv_rank_month -> {
                bookModels.clear()
                bookListAdapter.notifyDataSetChanged()
                typeUrl = monthRank
                currentPage = 0
                getBookList(0)
            }
            R.id.tv_rank_total -> {
                bookModels.clear()
                bookListAdapter.notifyDataSetChanged()
                typeUrl = totalRank
                currentPage = 0
                getBookList(0)
            }
            R.id.tv_type_over -> {
                bookModels.clear()
                currentPage = 0
                totalPageCount = 1
                bookListAdapter.notifyDataSetChanged()
                typeSmall = "over"
                getBookList(0)
            }
            R.id.tv_type_hot -> {
                bookModels.clear()
                currentPage = 0
                totalPageCount = 1
                bookListAdapter.notifyDataSetChanged()
                typeSmall = "hot"
                getBookList(0)
            }
            R.id.tv_type_repulation -> {
                bookModels.clear()
                currentPage = 0
                totalPageCount = 1
                bookListAdapter.notifyDataSetChanged()
                typeSmall = "reputation"
                getBookList(0)
            }
            R.id.tv_type_new -> {
                bookModels.clear()
                bookListAdapter.notifyDataSetChanged()
                typeSmall = "new"
                currentPage = 0
                totalPageCount = 1
                getBookList(0)
            }
        }
    }

    private fun getBookList(page: Int) = GlobalScope.launch(Dispatchers.Main) {

        val http = HttpUtil()
        if (typeUrl == "") {
            async(Dispatchers.Default) { http.httpGET1("https://api.zhuishushenqi.com/book/by-categories?gender=${gender}&type=${typeSmall}&major=${type}&start=${page}&limit=${limit}") }.await()
                    .let {

                        Log.d("type lis url:", "https://api.zhuishushenqi.com/book/by-categories?gender=${gender}&type=${typeSmall}&major=${type}&start=${page}&limit=${limit}")
                        val obj = JSONObject(it)
                        currentPage += limit
                        totalPageCount = obj.getString("total").toInt()
                        val listArray = obj.getJSONArray("books")
                        for (i in 0 until listArray.length()) {
                            val item = listArray.getJSONObject(i)

                            val bookModel = BookModel()
                            bookModel.coverUrl = item.getString("cover").replace("%3A", ":").replace("%2F", "/").replace("/agent/", "")
                            bookModel.name = item.getString("title")
                            bookModel.url = item.getString("_id")
                            bookModel.bookAuthor = item.getString("author")
                            bookModel.desc = item.getString("shortIntro")
                            bookModel.source = item.getString("site")
                            bookModels.add(bookModel)
                        }
                        bookListAdapter.notifyDataSetChanged()
                    }
        } else {
            totalPageCount = 0
            async(Dispatchers.Default) { http.httpGET1("http://api.zhuishushenqi.com/ranking/${typeUrl}") }.await()
                    .let {
                        Log.d("rank url:", "http://api.zhuishushenqi.com/ranking/${typeUrl}")
                        val obj = JSONObject(it)
                        val ranking = obj.getJSONObject("ranking")
                        val listArray = ranking.getJSONArray("books")
                        for (i in 0 until listArray.length()) {
                            val item = listArray.getJSONObject(i)

                            val bookModel = BookModel()
                            bookModel.coverUrl = item.getString("cover").replace("%3A", ":").replace("%2F", "/").replace("/agent/", "")
                            bookModel.name = item.getString("title")
                            bookModel.url = item.getString("_id")
                            bookModel.bookAuthor = item.getString("author")
                            bookModel.desc = item.getString("shortIntro")
                            bookModel.source = item.getString("site")
                            bookModels.add(bookModel)
                        }
                        bookListAdapter.notifyDataSetChanged()
                    }
        }


    }
}